<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="申领电子健康卡"
      left-text="返回"
      left-arrow
      @click-left="goBack"
      fixed
      placeholder
    />
    
    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 基础信息部分 -->
      <view class="form-section">
        <view class="section-title">基础信息</view>
        
        <!-- 证件类型 -->
        <van-cell
          title="证件类型"
          :value="certificateType"
          is-link
          @click="showCertificateTypePicker"
        />
        
        <!-- 认证方式 -->
        <van-cell title="认证方式">
          <template #value>
            <view class="auth-method">
              <van-radio-group v-model="authMethod" direction="horizontal">
                <van-radio name="upload">上传证件</van-radio>
                <van-radio name="face">人脸识别</van-radio>
              </van-radio-group>
            </view>
          </template>
        </van-cell>
        
        <!-- 姓名 -->
        <van-field
          v-model="formData.name"
          label="姓名"
          placeholder="请输入就诊人真实姓名"
          :rules="[{ required: true, message: '请输入姓名' }]"
        />
        
                 <!-- 证件号码 -->
         <van-field
           v-model="formData.idNumber"
           label="证件号码"
           placeholder="请输入就诊人证件号码"
           :rules="[
             { required: true, message: '请输入证件号码' },
             { validator: validateIdNumberLocal, message: '请输入正确的身份证号码' }
           ]"
         >
          <template #right-icon>
            <van-icon 
              name="photograph" 
              color="#07c160" 
              size="20"
              @click="scanIdCard"
            />
          </template>
        </van-field>
      </view>
      
      <!-- 协议同意部分 -->
      <view class="form-section">
        <view class="agreement-header">
          <text class="agreement-title">阅读并同意以下内容</text>
          <van-checkbox 
            v-model="agreedToTerms" 
            shape="circle"
            class="agreement-checkbox"
            @change="onAgreementChange"
            @click="toggleAgreement"
          />
        </view>
        
        <view class="agreement-text">
          您已知晓您在华医通的身份证件等个人信息,将用于您申领电子健康卡、预约挂号等所有需要实名制的场景,并在使用时进行验证,请确保此信息的真实有效。华医通将通过加密等方式保护此信息,且仅在具体业务流程中授权提供给第三方医疗卫生监管单位。
        </view>
        
        <!-- 测试区域 -->
        <view class="test-section">
          <van-button 
            type="warning" 
            size="small" 
            @click="testCheckbox"
            class="test-btn"
          >
            测试复选框状态
          </van-button>
          <van-button 
            type="success" 
            size="small" 
            @click="forceEnableNext"
            class="test-btn"
          >
            强制启用下一步
          </van-button>
          <van-button 
            type="danger" 
            size="small" 
            @click="clearMedicalCards"
            class="test-btn"
          >
            清除就诊卡
          </van-button>
          <text class="test-text">当前状态: {{ agreedToTerms ? '已同意' : '未同意' }}</text>
        </view>
      </view>
    </view>
    
    <!-- 底部按钮 -->
    <view class="bottom-action">
      <van-button 
        type="primary" 
        size="large" 
        block
        :disabled="!canProceed"
        @click="nextStep"
        class="next-btn"
      >
        下一步
      </van-button>
    </view>
    
    <!-- 证件类型选择器 -->
    <van-popup v-model:show="showCertificatePicker" position="bottom">
      <van-picker
        :columns="certificateTypes"
        @confirm="onCertificateTypeConfirm"
        @cancel="showCertificatePicker = false"
      />
    </van-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { validateIdNumber, maskIdNumber } from '@/utils/idCard'

// 表单数据接口
interface FormData {
  name: string
  idNumber: string
}

// 就诊卡接口定义
interface MedicalCard {
  id: string
  patientName: string
  maskedIdNumber: string
  isDefault: boolean
  isSelf: boolean
  idNumber?: string
}

// 响应式数据
const certificateType = ref('居民身份证')
const authMethod = ref('face')
const agreedToTerms = ref(false) // 取消勾选协议进行测试
const showCertificatePicker = ref(false)

const formData = ref<FormData>({
  name: '',
  idNumber: ''
})

// 模拟就诊卡数据（实际开发中应该从API获取）
const medicalCards = ref<MedicalCard[]>([
  {
    id: '1',
    patientName: '张三',
    maskedIdNumber: '320***********1234',
    idNumber: '320123456789012345',
    isDefault: true,
    isSelf: true
  },
  {
    id: '2', 
    patientName: '李四',
    maskedIdNumber: '320***********5678',
    idNumber: '320123456789015678',
    isDefault: false,
    isSelf: false
  }
])

// 证件类型选项
const certificateTypes = [
  '居民身份证',
  '护照',
  '军官证',
  '港澳通行证',
  '台湾通行证'
]

// 身份证号码正则表达式（备用）
const idNumberRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/

// 计算属性：是否可以进入下一步（临时移除协议验证）
const canProceed = computed(() => {
  const nameValid = formData.value.name.trim() !== ''
  const idNumberValid = formData.value.idNumber.trim() !== '' && validateIdNumberLocal(formData.value.idNumber) === true
  // const termsAgreed = agreedToTerms.value // 临时注释掉协议验证
  
  console.log('表单验证状态:', {
    name: formData.value.name,
    nameValid,
    idNumber: formData.value.idNumber,
    idNumberValid,
    // termsAgreed,
    // termsAgreedType: typeof termsAgreed,
    // termsAgreedValue: termsAgreed,
    canProceed: nameValid && idNumberValid // 临时移除协议验证
  })
  
  return nameValid && idNumberValid // 临时移除协议验证
})

// 显示证件类型选择器
const showCertificateTypePicker = () => {
  showCertificatePicker.value = true
}

// 确认证件类型选择
const onCertificateTypeConfirm = (value: string) => {
  certificateType.value = value
  showCertificatePicker.value = false
}

// 身份证号码验证（使用工具函数）
const validateIdNumberLocal = (value: string): boolean | string => {
  if (!value) return '请输入身份证号码'
  
  // 使用工具函数验证
  if (!validateIdNumber(value)) {
    return '身份证号码格式不正确'
  }
  
  return true
}



// 扫描身份证
const scanIdCard = () => {
  uni.showToast({
    title: '扫描功能开发中',
    icon: 'none'
  })
}

// 下一步
const nextStep = () => {
  if (!canProceed.value) {
    uni.showToast({
      title: '请完善信息并同意协议',
      icon: 'none'
    })
    return
  }
  
  // 保存就诊卡信息
  saveMedicalCard()
  
  // 跳转到下一步或返回
  uni.navigateBack()
}

// 保存就诊卡信息
const saveMedicalCard = () => {
  console.log('=== 保存就诊卡信息 ===')
  
  // 生成唯一的ID
  const newCardId = Date.now() + Math.random()
  
  const newCard = {
    id: newCardId,
    patientName: formData.value.name,
    idNumber: formData.value.idNumber,
    maskedIdNumber: maskIdNumber(formData.value.idNumber),
    isDefault: false,
    isSelf: true,
    createTime: new Date().toISOString()
  }
  
  console.log('新就诊卡信息:', newCard)
  
  try {
    // 获取现有就诊卡
    const existingCardsStr = uni.getStorageSync('medicalCards')
    console.log('现有就诊卡字符串:', existingCardsStr)
    
    let cards = []
    if (existingCardsStr) {
      try {
        cards = JSON.parse(existingCardsStr)
        console.log('解析后的现有就诊卡:', cards)
      } catch (parseError) {
        console.error('解析现有就诊卡失败:', parseError)
        cards = []
      }
    }
    
    // 检查是否已存在相同的身份证号码
    const existingCard = cards.find((card: any) => card.idNumber === formData.value.idNumber)
    if (existingCard) {
      console.log('发现重复的身份证号码:', existingCard)
      uni.showModal({
        title: '提示',
        content: '该身份证号码已存在就诊卡，是否要更新？',
        showCancel: true
      }).then((res) => {
        if (res.confirm) {
          // 更新现有卡
          const index = cards.findIndex((card: any) => card.idNumber === formData.value.idNumber)
          cards[index] = { ...existingCard, ...newCard }
          saveCardsToStorage(cards)
        }
      }).catch((error) => {
        console.error('显示确认对话框失败:', error)
      })
      return
    }
    
    // 添加新卡
    cards.push(newCard)
    console.log('添加新卡后的就诊卡列表:', cards)
    
    // 保存到本地存储
    saveCardsToStorage(cards)
    
  } catch (error) {
    console.error('保存就诊卡失败:', error)
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    })
  }
}

// 保存就诊卡到本地存储
const saveCardsToStorage = (cards: any[]) => {
  try {
    uni.setStorageSync('medicalCards', JSON.stringify(cards))
    console.log('成功保存到本地存储，共', cards.length, '张卡')
    
    uni.showToast({
      title: '就诊卡添加成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('保存到本地存储失败:', error)
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    })
  }
}

// 在保存成功后的处理函数中添加
const handleSaveSuccess = (newCard: MedicalCard) => {
  console.log('保存就诊卡成功:', newCard)
  
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options || {}
  
  if (options.returnTo === 'doctorSelect') {
    // 返回医生选择页面，并直接跳转到时间选择
    const url = `/pages/appointment/time-select?doctorId=${options.doctorId}&doctorName=${options.doctorName}&departmentName=${options.departmentName}&consultationPrice=${options.consultationPrice}&cardId=${newCard.id}&cardName=${encodeURIComponent(newCard.patientName)}&maskedIdNumber=${newCard.maskedIdNumber}`
    
    // 先返回医生选择页面，再跳转到时间选择
    uni.navigateBack({
      success: () => {
        setTimeout(() => {
          uni.navigateTo({
            url: url
          })
        }, 100)
      }
    })
  } else {
    // 其他情况直接返回
    uni.navigateBack()
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 页面加载
onLoad(() => {
  console.log('添加就诊卡页面 onLoad')
  console.log('初始状态 - agreedToTerms:', agreedToTerms.value)
})

// 监听复选框状态变化
const onAgreementChange = (event: any) => {
  console.log('协议同意状态变化事件:', event)
  console.log('事件类型:', event.type)
  console.log('复选框值:', event.detail)
  
  // 根据事件类型处理
  if (event.detail !== undefined) {
    agreedToTerms.value = event.detail
  } else if (typeof event === 'boolean') {
    agreedToTerms.value = event
  }
  
  console.log('设置后的 agreedToTerms.value:', agreedToTerms.value)
}

// 手动切换协议同意状态
const toggleAgreement = () => {
  console.log('点击复选框，当前状态:', agreedToTerms.value)
  agreedToTerms.value = !agreedToTerms.value
  console.log('切换后状态:', agreedToTerms.value)
}

// 测试复选框状态
const testCheckbox = () => {
  console.log('=== 复选框状态测试 ===')
  console.log('agreedToTerms.value:', agreedToTerms.value)
  console.log('agreedToTerms.value 类型:', typeof agreedToTerms.value)
  console.log('agreedToTerms.value === true:', agreedToTerms.value === true)
  console.log('agreedToTerms.value === false:', agreedToTerms.value === false)
  console.log('!agreedToTerms.value:', !agreedToTerms.value)
  
  // 强制设置为 true
  agreedToTerms.value = true
  console.log('强制设置为 true 后:', agreedToTerms.value)
}

// 强制启用下一步（临时测试用）
const forceEnableNext = () => {
  console.log('=== 强制启用下一步测试 ===')
  
  // 填充测试数据（使用有效的身份证号码）
  formData.value.name = '测试用户'
  formData.value.idNumber = '511623200001035550' // 这个号码需要是有效的
  
  console.log('填充测试数据后:')
  console.log('姓名:', formData.value.name)
  console.log('身份证:', formData.value.idNumber)
  
  // 验证身份证号码
  const idNumberValid = validateIdNumberLocal(formData.value.idNumber)
  console.log('身份证验证结果:', idNumberValid)
  
  console.log('canProceed.value:', canProceed.value)
  
  // 强制触发计算属性重新计算
  console.log('表单验证状态应该变为:')
  console.log('nameValid: true')
  console.log('idNumberValid:', idNumberValid)
  console.log('canProceed:', canProceed.value)
}

// 清除就诊卡（测试用）
const clearMedicalCards = () => {
  console.log('=== 清除就诊卡 ===')
  
  uni.showModal({
    title: '确认清除',
    content: '确定要清除所有就诊卡吗？此操作不可恢复！',
    showCancel: true
  }).then((res) => {
    if (res.confirm) {
      try {
        uni.removeStorageSync('medicalCards')
        console.log('已清除所有就诊卡')
        
        uni.showToast({
          title: '就诊卡已清除',
          icon: 'success'
        })
      } catch (error) {
        console.error('清除就诊卡失败:', error)
        uni.showToast({
          title: '清除失败',
          icon: 'none'
        })
      }
    }
  }).catch((error) => {
    console.error('显示确认对话框失败:', error)
  })
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.main-content {
  padding: 20rpx;
}

.form-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.agreement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.agreement-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.agreement-checkbox {
  flex-shrink: 0;
}

.auth-method {
  .van-radio-group {
    display: flex;
    gap: 40rpx;
  }
}

.agreement-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
  text-align: justify;
}

.test-section {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-top: 20rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
}

.test-btn {
  background: #ff9500;
  border: none;
  border-radius: 20rpx;
  height: 60rpx;
  font-size: 24rpx;
}

.test-text {
  font-size: 26rpx;
  color: #333;
  font-weight: bold;
}

.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background: white;
  border-top: 1rpx solid #f0f0f0;
}

.next-btn {
  background: #07c160;
  border: none;
  border-radius: 25rpx;
  height: 88rpx;
  font-size: 32rpx;
  font-weight: bold;
  
  &:disabled {
    background: #ccc;
  }
}

// 自定义van-field样式
:deep(.van-field__label) {
  color: #333;
  font-weight: 500;
}

:deep(.van-field__input) {
  color: #333;
}

:deep(.van-field__placeholder) {
  color: #999;
}
</style>
